﻿using System;
using System.Collections.Generic;
using System.Text;
using IrisGenerator.Framework.Reflection;
using System.Reflection;

namespace IrisGenerator.Framework.UI.Controls
{
    public class BindableTextBox:System.Windows.Forms.TextBox,IBindableControl
    {
        public BindableTextBox()
            : base()
        {
            this.Load += new EventHandler(BindableTextBox_Load);
        }

        void BindableTextBox_Load(object sender, EventArgs e)
        {
            this.LoadSource();   
        }

        public void LoadSource()
        {
            if (this.SourceMethod != null && !this.DesignMode)
            {
                if (string.IsNullOrEmpty(this.ParentSourceProperty))
                    return;

                if (this.Parent != null)
                {
                    PropertyInfo pi=this.Parent.GetType().GetProperty(this.ParentSourceProperty);
                    if (pi != null)
                        this.Text = pi.GetValue(this.Parent, null) as string;
                    }
                }
            }
        


        public string ParentSourceProperty { get; set; }
        public MethodCall SourceMethod { get; set; }

        public event EventHandler Load;

        private bool _calledOnLoad;

        protected void OnLoad(EventArgs e)
        {
            if (this.Load != null)
                this.Load(this, e);
        }

        protected override void OnCreateControl()
        {
            base.OnCreateControl();
            if (!_calledOnLoad)
            {
                this._calledOnLoad = true;
                this.OnLoad(EventArgs.Empty);
            }
        }
    }
}
